//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package me.work.pay.jsyl.app.utils;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.AdvertiseSettings.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;

import com.chaomeng.a8sdklibrary.bluetooth.Const;
import com.chaomeng.a8sdklibrary.event.CloseBleEvent;
import com.chaomeng.a8sdklibrary.event.WifiInfoEvent;
import com.chaomeng.a8sdklibrary.utils.LogUtil;
import com.triumen.libble.core.BlePeripheralPacker;
import com.triumen.libble.core.BlePeripheralParser;
import com.triumen.libble.core.BleServiceProfile;
import com.triumen.libble.core.base.BaseBleParser.BaseBleParserListener;
import com.triumen.libble.entity.NetworkInfo;
import com.triumen.libble.entity.NetworkSpeedInfo;
import com.triumen.libble.util.CommonUtils;
import com.triumen.libble.util.NetworkHelper;
import com.triumen.libble.util.PingUtils;
import com.triumen.libble.util.WiFiUtils;
import com.triumen.libble.util.NetworkHelper.OnNetworkTestResultListener;
import com.triumen.libble.util.NetworkHelper.OnSpeedResultListener;
import com.triumen.libble.util.PingUtils.OnPingResultListener;
import java.util.Queue;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

@RequiresApi(
    api = 18
)
public class SBleService extends Service {
    private static final String TAG = "BleService";
    private BluetoothAdapter mBlueToothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothManager mBluetoothManager;
    private BluetoothGattServer mGattServer;
    private BluetoothGattCharacteristic characteristicRead;
    AdvertiseCallback callback;
    BluetoothLeAdvertiser bluetoothLeAdvertiser;
    private BluetoothGattServerCallback bluetoothGattServerCallback = new BluetoothGattServerCallback() {
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            LogUtil.e("BleService", String.format("1.onConnectionStateChange：device name = %s, address = %s", device.getName(), device.getAddress()));
            LogUtil.e("BleService", String.format("1.onConnectionStateChange：status = %s, newState =%s ", status, newState));
            super.onConnectionStateChange(device, status, newState);
        }

        public void onServiceAdded(int status, BluetoothGattService service) {
            super.onServiceAdded(status, service);
            LogUtil.e("BleService", String.format("onServiceAdded：status = %s", status));
        }

        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
            LogUtil.e("BleService", String.format("onCharacteristicReadRequest：device name = %s, address = %s", device.getName(), device.getAddress()));
            LogUtil.e("BleService", String.format("onCharacteristicReadRequest：requestId = %s, offset = %s", requestId, offset));
            SBleService.this.mGattServer.sendResponse(device, requestId, 0, offset, characteristic.getValue());
        }

        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] requestBytes) {
            LogUtil.e("BleService", String.format("3.onCharacteristicWriteRequest：device name = %s, address = %s", device.getName(), device.getAddress()));
            LogUtil.e("BleService", String.format("3.onCharacteristicWriteRequest：requestId = %s, preparedWrite=%s, responseNeeded=%s, offset=%s, value=%s", requestId, preparedWrite, responseNeeded, offset, requestBytes.toString()));
            SBleService.this.mGattServer.sendResponse(device, requestId, 0, offset, requestBytes);
            SBleService.this.onResponseToClient(requestBytes, device, requestId, characteristic);
        }

        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            LogUtil.e("BleService", String.format("2.onDescriptorWriteRequest：device name = %s, address = %s", device.getName(), device.getAddress()));
            LogUtil.e("BleService", String.format("2.onDescriptorWriteRequest：requestId = %s, preparedWrite = %s, responseNeeded = %s, offset = %s, value = %s,", requestId, preparedWrite, responseNeeded, offset, value.toString()));
            SBleService.this.mGattServer.sendResponse(device, requestId, 0, offset, value);
        }

        public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
            SBleService.this.mGattServer.sendResponse(device, requestId, 0, offset, (byte[])null);
        }

        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device, status);
            if (status == 0) {
                LogUtil.i("BleService", "onNotificationSent success");
            }

        }

        public void onMtuChanged(BluetoothDevice device, int mtu) {
            super.onMtuChanged(device, mtu);
            LogUtil.e("BleService", String.format("onMtuChanged：mtu = %s", mtu));
        }

        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
            super.onExecuteWrite(device, requestId, execute);
            LogUtil.e("BleService", String.format("onExecuteWrite：requestId = %s", requestId));
        }
    };

    public SBleService() {
    }

    @RequiresApi(
        api = 21
    )
    public void onCreate() {
        super.onCreate();
        LogUtil.i("BleService", "onCreate");
    }

    @RequiresApi(
        api = 21
    )
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.i("BleService", "onStartCommand");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        this.mBluetoothManager = (BluetoothManager)this.getSystemService("bluetooth");
        this.initGATTServer();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(
        api = 21
    )
    private void initGATTServer() {
        LogUtil.i("BleService", "initGATTServer");
        AdvertiseSettings settings = (new Builder()).setConnectable(true).build();
        AdvertiseData advertiseData = (new android.bluetooth.le.AdvertiseData.Builder()).setIncludeDeviceName(true).setIncludeTxPowerLevel(true).build();
        AdvertiseData scanResponseData = (new android.bluetooth.le.AdvertiseData.Builder()).addServiceUuid(new ParcelUuid(Const.UUID_SERVICE)).setIncludeTxPowerLevel(true).build();
        this.callback = new AdvertiseCallback() {
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                LogUtil.d("BleService", "BLE advertisement added successfully");
                SBleService.this.initServices(SBleService.this);
            }

            public void onStartFailure(int errorCode) {
                LogUtil.e("BleService", "Failed to add BLE advertisement, reason: " + errorCode);
            }
        };
        this.bluetoothLeAdvertiser = this.mBlueToothAdapter.getBluetoothLeAdvertiser();
        if (this.bluetoothLeAdvertiser == null) {
            LogUtil.i("BleService", "BluetoothLeAdvertiser为null");
        }

        if (this.bluetoothLeAdvertiser != null) {
            LogUtil.i("BleService", "startAdvertising");
            this.bluetoothLeAdvertiser.startAdvertising(settings, advertiseData, scanResponseData, this.callback);
        }

    }

    @RequiresApi(
        api = 18
    )
    private void initServices(Context context) {
        this.mGattServer = this.mBluetoothManager.openGattServer(context, this.bluetoothGattServerCallback);
        LogUtil.i("BleService", "mGattServer : " + this.mGattServer);
        BluetoothGattService service = new BluetoothGattService(Const.UUID_SERVICE, 0);
        LogUtil.i("BleService", "service : " + service);
        this.characteristicRead = new BluetoothGattCharacteristic(Const.UUID_CHARACTERISTIC_READ, 18, 1);
        BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(Const.UUID_DESCRIPTOR, 16);
        this.characteristicRead.addDescriptor(descriptor);
        service.addCharacteristic(this.characteristicRead);
        BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(Const.UUID_CHARACTERISTIC_WRITE, 26, 16);
        service.addCharacteristic(characteristicWrite);
        this.mGattServer.addService(BleServiceProfile.addCharacteristic(service));
        LogUtil.e("BleService", "2. initServices ok");
    }

    @RequiresApi(
        api = 21
    )
    private void onResponseToClient(byte[] requestBytes, final BluetoothDevice device, int requestId, final BluetoothGattCharacteristic characteristic) {
        if (BleServiceProfile.UUID_CHARACTERISTIC_WRITE.equals(characteristic.getUuid())) {
            BlePeripheralParser.getInstance().parser(requestBytes, new BaseBleParserListener() {
                public void onParserDone(String cmdType, String text) {
                    byte var4 = -1;
                    switch(cmdType.hashCode()) {
                    case 1584:
                        if (cmdType.equals("1A")) {
                            var4 = 0;
                        }
                        break;
                    case 1585:
                        if (cmdType.equals("1B")) {
                            var4 = 1;
                        }
                        break;
                    case 1586:
                        if (cmdType.equals("1C")) {
                            var4 = 2;
                        }
                        break;
                    case 1587:
                        if (cmdType.equals("1D")) {
                            var4 = 3;
                        }
                        break;
                    case 1588:
                        if (cmdType.equals("1E")) {
                            var4 = 4;
                        }
                    case 1589:
                    case 1590:
                    case 1591:
                    case 1592:
                    case 1593:
                    case 1594:
                    case 1595:
                    case 1596:
                    case 1597:
                    default:
                        break;
                    case 1598:
                        if (cmdType.equals("20")) {
                            var4 = 5;
                        }
                    }

                    switch(var4) {
                    case 0:
                        String hexString = BlePeripheralPacker.getInstance().packWifiName(WiFiUtils.getWifiName(SBleService.this));
                        SBleService.this.sendDataToClient(hexString, characteristic, device);
                        break;
                    case 1:
                        String hexString1 = BlePeripheralPacker.getInstance().packWifiStrength(WiFiUtils.getWifiStrength(SBleService.this));
                        SBleService.this.sendDataToClient(hexString1, characteristic, device);
                        break;
                    case 2:
                        NetworkHelper.getInstance(SBleService.this).asyncSpeed(new OnSpeedResultListener() {
                            public void onSpeedSuccess(NetworkSpeedInfo networkSpeedInfo) {
                                String hexString = BlePeripheralPacker.getInstance().packNetworkSpeed(networkSpeedInfo.toString());
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }

                            public void onSpeedFailure(String message) {
                                String hexString = BlePeripheralPacker.getInstance().packNetworkSpeed(message);
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }
                        });
                        break;
                    case 3:
                        PingUtils.asyncGetPingResult("https://www.baidu.com", new OnPingResultListener() {
                            public void onPingSuccess(String pingResult) {
                                String hexString = BlePeripheralPacker.getInstance().packDelayRate(pingResult);
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }

                            public void onPingFailure() {
                                String time = "PING失败，请重试";
                                String hexString = BlePeripheralPacker.getInstance().packDelayRate(time);
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }
                        });
                        break;
                    case 4:
                        NetworkHelper.getInstance(SBleService.this).asyncNetworkTest((String)null, (String)null, new OnNetworkTestResultListener() {
                            public void onNetworkTestSuccess(NetworkInfo NetworkInfo) {
                                String hexString = BlePeripheralPacker.getInstance().packNetworkTest(NetworkInfo.toString());
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }

                            public void onNetworkTestFailure() {
                                String time = "测试网络操作时间失败，请重试";
                                String hexString = BlePeripheralPacker.getInstance().packNetworkTest(time);
                                SBleService.this.sendDataToClient(hexString, characteristic, device);
                            }
                        });
                    case 5:
                    }

                }

                public void onParserFailed() {
                }
            });
        } else if (Const.UUID_CHARACTERISTIC_WRITE.equals(characteristic.getUuid())) {
            String str = new String(requestBytes);
            LogUtil.e("BleService", "4.收到：" + str);
            String ssid = null;
            String pswd = null;
            String bssid = null;
            String newstr = str.substring(str.indexOf(":") + 1);
            String[] parmas = newstr.split(",");
            if (parmas.length == 3) {
                ssid = parmas[0];
                pswd = parmas[1];
                bssid = parmas[2];
            } else if (str != null) {
                ssid = str.substring(str.indexOf(":") + 1, str.indexOf(","));
                pswd = str.substring(str.indexOf(",") + 1);
                bssid = "";
            }

            LogUtil.i("BleService", "ssid : " + ssid + "    pswd : " + pswd + "  bssid : " + bssid);
            EventBus.getDefault().post(new WifiInfoEvent(bssid, ssid, pswd));
            this.characteristicRead.setValue(str.getBytes());
            this.mGattServer.notifyCharacteristicChanged(device, this.characteristicRead, false);
        } else {
            LogUtil.i("BleService", "Invalid Characteristic Write: " + characteristic.getUuid());
            this.mGattServer.sendResponse(device, requestId, 257, 0, (byte[])null);
        }

    }

    private void sendDataToClient(String hexString, BluetoothGattCharacteristic characteristic, BluetoothDevice device) {
        if (!TextUtils.isEmpty(hexString)) {
            byte[] bytes = CommonUtils.hexString2Bytes(hexString);
            Queue<byte[]> dataQueue = CommonUtils.splitByte(bytes);

            for(byte[] sendData = (byte[])dataQueue.poll(); sendData != null; sendData = (byte[])dataQueue.poll()) {
                characteristic.setValue(sendData);
                this.mGattServer.notifyCharacteristicChanged(device, characteristic, false);
            }
        } else {
            LogUtil.d("BleService", "sendDataToClient: hexString can not be empty.");
        }

    }

    public void onDestroy() {
        super.onDestroy();
    }

    @Subscribe(
        threadMode = ThreadMode.MAIN
    )
    public void onCloseBle(CloseBleEvent event) {
        this.stopAdvertising();
    }

    public void stopAdvertising() {
        LogUtil.d("BleService", "stopAdvertising");
        if(this.mGattServer!=null) {
            this.mGattServer.clearServices();
            this.mGattServer.close();
        }
        if (this.bluetoothLeAdvertiser != null) {
            this.bluetoothLeAdvertiser.stopAdvertising(this.callback);
            this.callback = null;
        }

        EventBus.getDefault().unregister(this);
        LogUtil.d("BleService", "服务停止广播");
        this.stopSelf();
    }
}
